import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_is_know_dialog.dart';
import 'package:e_reception_flutter/media_library/media_library_index/media_library_index_view_model.dart';
import 'package:e_reception_flutter/singleton/theme_repository/color_constants.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/building_index/create_building_index_page.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/system_ui_utils.dart';
import 'package:e_reception_flutter/vg_widgets/light_annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_place_holder_status_widget/vg_place_holder_status_widget.dart';
import 'package:e_reception_flutter/vg_widgets/vg_top_bar_widget/vg_top_bar_widget.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_log_lib.dart';
import 'package:webview_flutter/webview_flutter.dart';

import 'building_index_module_list_response_bean.dart';
import 'building_index_view_model.dart';

///楼层指引模板详情
class BuildingIndexModelDetailPage extends StatefulWidget{
  ///路由名称
  static const String ROUTER = "BuildingIndexModelDetailPage";

  final BuildingIndexModuleBean detailInfo;
  const BuildingIndexModelDetailPage(
      {Key key, this.detailInfo}) : super(key:key);

  @override
  _BuildingIndexModelDetailPageState createState() =>_BuildingIndexModelDetailPageState();

  static Future<dynamic> navigatorPush(BuildContext context, BuildingIndexModuleBean detailInfo){
    return RouterUtils.routeForFutureResult(
        context,
        BuildingIndexModelDetailPage(detailInfo: detailInfo,),
        routeName: BuildingIndexModelDetailPage.ROUTER
    );
  }

}

class _BuildingIndexModelDetailPageState extends BaseState<BuildingIndexModelDetailPage>{
  BuildingIndexViewModel _viewModel;
  WebViewController _webViewController;
  //webview加载成功
  bool isUrlLoadComplete = false;
  BuildingIndexModuleBean _detailInfo;
  String _loadUrl;
  @override
  void initState() {
    super.initState();
    _detailInfo = widget?.detailInfo;
    _viewModel = BuildingIndexViewModel(this);
    _viewModel?.statusTypeValueNotifier?.value = null;
    _loadUrl = _detailInfo.htmlurl;
    String contentJson = '{"comWbrand":{"id":"2949d8c58e1746dab3a942f1b6ef3270","companyid":"5097e6cbbe544fde99df5685871818cb","syswid":"3","htmlurl":"http://etpic.we17.com/test/20220112133230_4299.html","picurl":"http://etpic.we17.com/test/20220114174127_8794.jpg","wtitle":"蓝天大厦3号楼","upflg":"01","usnum":1,"uenum":27,"dflg":"00","dsnum":0,"denum":0,"createuid":"4a3d21386acb4f3d923227515c130470","createtime":"2022-01-14 17:18:57","updatetime":"2022-01-14 17:41:23"},"upList":[{"fnum":"3","floorflg":"02","company":"中国移动北京分公司","id":"5f1bc1602007474b93372270e48d666e","comwid":"2949d8c58e1746dab3a942f1b6ef3270","hnum":"3003"},{"fnum":"29","floorflg":"02","company":"北京字节跳动科技有限公司","id":"780e077c20884c8c98126a48fe3c17a7","comwid":"2949d8c58e1746dab3a942f1b6ef3270","hnum":"2908"},{"fnum":"29","floorflg":"02","company":"北京湛腾世纪科技有限公司","id":"921270866c5a4286b0618255e8384a8d","comwid":"2949d8c58e1746dab3a942f1b6ef3270","hnum":"2909"},{"fnum":"28","floorflg":"02","company":"阿里巴巴集团","id":"8b48467004b34b418b4edc6edaa5c233","comwid":"2949d8c58e1746dab3a942f1b6ef3270","hnum":"2801"},{"fnum":"28","floorflg":"02","company":"深圳市腾讯计算机系统有限公司","id":"3bbe477405114126af6e18c7d3cc2720","comwid":"2949d8c58e1746dab3a942f1b6ef3270","hnum":"2802"},{"fnum":"27","floorflg":"02","company":"幻电科技有限公司","id":"5be7c121b9754cac826946b8be1cbf3c","comwid":"2949d8c58e1746dab3a942f1b6ef3270","hnum":"2701"},{"fnum":"27","floorflg":"02","company":"华为技术有限公司","id":"4e302b1081354118be2e906edb84182a","comwid":"2949d8c58e1746dab3a942f1b6ef3270","hnum":"2702"},{"fnum":"27","floorflg":"02","company":"OPPO技术有限公司","id":"e72e9242da5f43e7971623b1435094b2","comwid":"2949d8c58e1746dab3a942f1b6ef3270","hnum":"2703"},{"fnum":"26","floorflg":"02","company":"VIVO技术有限公司","id":"47a8d64b75384deda8f09ec6a46a0a66","comwid":"2949d8c58e1746dab3a942f1b6ef3270","hnum":"2601"},{"fnum":"26","floorflg":"02","company":"维沃移动通信有限公司","id":"9e35f36544bb4693950b7ea05e096789","comwid":"2949d8c58e1746dab3a942f1b6ef3270","hnum":"2602"},{"fnum":"25","floorflg":"02","company":"博尔迈兴机械设备有限公司","id":"092e0f05e1334247a25e00fb504b9239","comwid":"2949d8c58e1746dab3a942f1b6ef3270","hnum":"2501"},{"fnum":"25","floorflg":"02","company":"禧年光电科技有限公司","id":"4676de7585ff46adaeee94d3f5eed8d1","comwid":"2949d8c58e1746dab3a942f1b6ef3270","hnum":"2502"},{"fnum":"24","floorflg":"02","company":"字节跳动有限公司","id":"97a793280fa9409ca857a6536c73c2bc","comwid":"2949d8c58e1746dab3a942f1b6ef3270","hnum":"2401"},{"fnum":"24","floorflg":"02","company":"辰邦集团","id":"9bbcff31fb9f4acc949e255189e8edbf","comwid":"2949d8c58e1746dab3a942f1b6ef3270","hnum":"2402"},{"fnum":"23","floorflg":"02","company":"小米集团","id":"98807b783ee841ada28a5e46e43c0ea9","comwid":"2949d8c58e1746dab3a942f1b6ef3270","hnum":"2301"},{"fnum":"23","floorflg":"02","company":"华为集团","id":"ead878f20693409c82ea5a3ac0ea0a03","comwid":"2949d8c58e1746dab3a942f1b6ef3270","hnum":"2302"},{"fnum":"22","floorflg":"02","company":"联通集团","id":"5c4c6f7427414189bd4a240285249e59","comwid":"2949d8c58e1746dab3a942f1b6ef3270","hnum":""},{"fnum":"21","floorflg":"02","company":"西门子数控有限公司","id":"ca9dcb1a674d44dcafc2b8a9f40f6a1d","comwid":"2949d8c58e1746dab3a942f1b6ef3270","hnum":"2101"},{"fnum":"21","floorflg":"02","company":"甲骨文公司","id":"238a01d2129e493d92c2fbcff73633b5","comwid":"2949d8c58e1746dab3a942f1b6ef3270","hnum":"2102"},{"fnum":"20","floorflg":"02","company":"IBM","id":"169f755d15d7400f90bf1421b48e2048","comwid":"2949d8c58e1746dab3a942f1b6ef3270","hnum":"2001"},{"fnum":"2","floorflg":"02","company":"链家房地产集团","id":"9ed53ba526d848e2ab9cce82dfc1a760","comwid":"2949d8c58e1746dab3a942f1b6ef3270","hnum":"2001"},{"fnum":"2","floorflg":"02","company":"万达集团","id":"d3725dd1ad844bbc8c2b0f339337f768","comwid":"2949d8c58e1746dab3a942f1b6ef3270","hnum":"2002"},{"fnum":"19","floorflg":"02","company":"小米","id":"d72d02b3e2ec4dcca8cd8394a6bee5e7","comwid":"2949d8c58e1746dab3a942f1b6ef3270","hnum":"1901"},{"fnum":"18","floorflg":"02","company":"ThinkPad","id":"d45b7798f14c4c918e7ba97c1224d736","comwid":"2949d8c58e1746dab3a942f1b6ef3270","hnum":"1801"},{"fnum":"17","floorflg":"02","company":"Apple中国","id":"45e3368441ea4d3996e15b4eeb029c2d","comwid":"2949d8c58e1746dab3a942f1b6ef3270","hnum":"1701"},{"fnum":"16","floorflg":"02","company":"联想机器","id":"9e02a39a6e5644818232e10c62ef07df","comwid":"2949d8c58e1746dab3a942f1b6ef3270","hnum":"1601"},{"fnum":"1","floorflg":"02","company":"北京天健会计","id":"1aed246d15a343c3982d92ad81bb8528","comwid":"2949d8c58e1746dab3a942f1b6ef3270","hnum":"1001"},{"fnum":"1","floorflg":"02","company":"北京湛腾世纪科技有限公司","id":"77c3dae52319436090634cf8d53b90a3","comwid":"2949d8c58e1746dab3a942f1b6ef3270","hnum":"1002"}],"downList":[{"fnum":"1","floorflg":"01","company":"嘉禾舞社","id":"2f84889a3ea141eb89f2993d6bd1baf5","comwid":"c9d40e751d1f46c6970746a3838388c1","hnum":"B101"},{"fnum":"1","floorflg":"01","company":"裕泽园美食汇","id":"173cbcadd7a64116b51fa8add9660751","comwid":"c9d40e751d1f46c6970746a3838388c1","hnum":"B102"},{"fnum":"2","floorflg":"01","company":"永辉超市","id":"2b03bb997a9e4b4eb64a0a64cffc973f","comwid":"c9d40e751d1f46c6970746a3838388c1","hnum":""}]}';
    _loadUrl += '?containerFlg=01&contJson=' + Uri.encodeComponent(contentJson);
  }

  @override
  Widget build(BuildContext context) {
    return LightAnnotatedRegion(
        child: Scaffold(
          backgroundColor: Colors.white,
          resizeToAvoidBottomPadding: false,
          resizeToAvoidBottomInset: false,
          body: Stack(
            children: [
              Column(
                  children:[
                    _toTopBarWidget(),
                    Expanded(
                        child: ValueListenableBuilder(
                        valueListenable: _viewModel?.statusTypeValueNotifier,
                        builder:
                            (BuildContext context, PlaceHolderStatusType value, Widget child) {
                          return VgPlaceHolderStatusWidget(
                            loadingStatus: value == PlaceHolderStatusType.loading,
                            errorStatus: value == PlaceHolderStatusType.error,
                            emptyStatus: value == PlaceHolderStatusType.empty,
                            errorOnClick: () => setState(() {
                              _viewModel?.statusTypeValueNotifier?.value = null;
                            }),
                            loadingOnClick: () => setState(() {
                              _viewModel?.statusTypeValueNotifier?.value = null;
                            }),
                            emptyCustomWidget: _defaultEmptyCustomWidget("暂无内容"),
                            errorCustomWidget: _defaultEmptyCustomWidget("网络断线 重新获取"),
                            child: child,
                          );
                        },
                        child: _toWebViewWidget())
                    ),
                  ]),
              _toBottomWidget(),
            ],
          ),
        )
    );
  }

  Widget _toTopBarWidget(){
    return VgTopBarWidget(
      isShowBack: true,
      title: "楼层指示牌",
      titleColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
    );
  }

  Widget _defaultEmptyCustomWidget(String msg) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: <Widget>[
        Image.asset(
          "images/icon_empty_white.png",
          width: 120,
          gaplessPlayback: true,
        ),
        SizedBox(
          height: 8,
        ),
        Text(
          msg??"暂无内容",
          maxLines: 1,
          overflow: TextOverflow.ellipsis,
          style: TextStyle(
            color: VgColors.INPUT_BG_COLOR,
            fontSize: 13,
          ),
        )
      ],
    );
  }

  Widget _toBottomWidget(){
    double bottomH = ScreenUtils.getBottomBarH(context);
    return Align(
      alignment: Alignment.bottomCenter,
      child: Container(
        height: 60 + bottomH,
        color: Colors.white,
        alignment: Alignment.center,
        padding: EdgeInsets.only(left: 15, right: 15, bottom: bottomH),
        child: GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: (){
            //00创建 01编辑
            // RouterUtils.pop(context);
            CreateBuildingIndexPage.navigatorPush(context, "00", _detailInfo?.id);
          },
          child: ClipRRect(
            borderRadius: BorderRadius.circular(4),
            child: Container(
              height: 40,
              alignment: Alignment.center,
              color: ThemeRepository.getInstance().getPrimaryColor_1890FF(),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Text(
                    "使用该模板，去制作",
                    style: TextStyle(
                        color: Colors.white,
                        fontSize: 15
                    ),
                  ),
                  SizedBox(width: 4,),
                  Image.asset('images/icon_arrow_white.png', width: 6,),
                ],
              ),
            ),
          ),
        ),
      ),
    );
  }

  Widget _toWebViewWidget() {
    double maxHeight = ScreenUtils.screenH(context) -
        ScreenUtils.getStatusBarH(context) -
        ScreenUtils.getBottomBarH(context) -
        15 -
        50 -
        44;
    double screenWidth = ScreenUtils.screenW(context) - 30;
    double width;
    double height;
    if (maxHeight / screenWidth <= 16 / 9) {
      width = maxHeight / (16 / 9);
      height = maxHeight;
    } else {
      width = screenWidth;
      height = screenWidth * (16 / 9);
    }
    print("屏幕宽： ${screenWidth}");
    print("屏幕高： ${maxHeight}");
    print("真实宽： ${width}");
    print("真实高： ${height}");
    print("url:$_loadUrl");
    // print("statusTypeValueNotifier0:" + (_viewModel?.statusTypeValueNotifier?.value == PlaceHolderStatusType.loading).toString());
    // print("statusTypeValueNotifier1:" + (_viewModel?.statusTypeValueNotifier?.value == PlaceHolderStatusType.error).toString());
    // print("statusTypeValueNotifier2:" + (_viewModel?.statusTypeValueNotifier?.value == PlaceHolderStatusType.empty).toString());
    return Container(
      color: Colors.white,
      margin: EdgeInsets.only(left: 15, right: 15),
      padding: EdgeInsets.only(bottom: 60),
      child: ClipRRect(
        borderRadius: BorderRadius.only(topLeft: Radius.circular(8), topRight: Radius.circular(8)),
        child: Stack(
          children: [
            Opacity(
              opacity: isUrlLoadComplete ? 1 : 0,
              child: WebView(
                initialUrl: _loadUrl,
                javascriptMode: JavascriptMode.unrestricted,
                javascriptChannels: <JavascriptChannel>[
                ].toSet(),
                onPageFinished: (String url) {
                  print("加载完成\n" + url);
                  if(!(isUrlLoadComplete??false)){
                    setState(() {
                      isUrlLoadComplete = true;
                    });
                  }
                },
                onWebViewCreated: (controller) {
                  _webViewController = controller;
                },
                onWebResourceError: (error){
                  print("加载失败：" + error?.description??"");
                  String errorInfo = error?.description??"";
                  if(errorInfo.contains("net::ERR_INTERNET_DISCONNECTED")
                      || errorInfo.contains("404")
                      || errorInfo.contains("500")
                      || errorInfo.contains("Error")
                      || errorInfo.contains("找不到网页")
                      || errorInfo.contains("网页无法打开")){
                    _viewModel?.statusTypeValueNotifier?.value = PlaceHolderStatusType.error;
                  }
                },
              ),
            ),
            Center(
              child: Visibility(
                visible: !isUrlLoadComplete,
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    CircularProgressIndicator(
                      strokeWidth: 2,
                    ),
                    SizedBox(
                      height: 10,
                    ),
                    Text(
                      "正在加载",
                      style: TextStyle(
                          color: ThemeRepository.getInstance()
                              .getCardBgColor_21263C(),
                          fontSize: 10),
                    )
                  ],
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

}